#include "hash_lock.h"
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "stdio.h"

#define TAG_COUNT 3  // 假设有3个标签

// 模拟数据库存储的标签信息
typedef struct {
    uint8_t ID[4];
    uint8_t locked; // 0表示未锁定，1表示已锁定
} TagInfo;

TagInfo database[TAG_COUNT] = {
    {{0x01, 0x02, 0x03, 0x04}, 0},
    {{0x05, 0x06, 0x07, 0x08}, 0},
    {{0x09, 0x0A, 0x0B, 0x0C}, 0}
};

// 随机数发生器函数，生成一个随机数
uint8_t generate_random_number() {
    return rand() % 256;
}

// 哈希函数，这里简单用 XOR 代替
void compute_hash(uint8_t *input, uint8_t length, uint8_t *output) {
    uint8_t hash = 0;
    for (uint8_t i = 0; i < length; i++) {
        hash ^= input[i];
    }
    *output = hash;
}

// 验证标签
int verify_tag(uint8_t *ID, uint8_t random_number, uint8_t received_hash) {
    uint8_t computed_hash;
    uint8_t combined[5];

    // 将ID和随机数连接起来
    memcpy(combined, ID, 4);
    combined[4] = random_number;

    // 计算 hash(ID || R)
    compute_hash(combined, 5, &computed_hash);

    printf("Computed Hash: 0x%02X\n", computed_hash);
    printf("Received Hash: 0x%02X\n", received_hash);
    printf("Generated Random Number: %X\r\n", random_number);

    // 比较计算出的 hash 值和接收到的 hash 值
    if (computed_hash == received_hash) {
        return 1; // 标签验证成功
    }

    return 0; // 验证失败
}
